<?php
namespace  common\components\services\goods;

use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\components\helpers\Tree;
use common\models\datas\Cate;
use common\models\datas\CateAttr;
use frontend\models\datas\Goods;
use frontend\models\datas\Mechanic;
use yii\base\Action;
use yii\data\Pagination;
use yii\helpers\Json;
use yii\web\BadRequestHttpException;
use yii\web\Response;

class GoodsIndexAction extends Action{

    public $type;

    public function run(){
        $role=isset(\Yii::$app->user->identity->role)?\Yii::$app->user->identity->role:'';
        $this->type= \Yii::$app->request->get('type_id');
        if(empty($this->type)){
            throw new BadRequestHttpException(\Yii::t('frontend', '商品类型不存在'));
        }
        $tree=$this->getCategory($this->type);
        if (\Yii::$app->request->isAjax) {
            if (\Yii::$app->request->get('type_id') == null) {
                throw new BadRequestHttpException(\Yii::t('frontend', '商品类型不存在'));
             }
            if (\Yii::$app->request->post('param') != null) $param = Json::decode(\Yii::$app->request->post('param'));
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $pageSize = !empty($param['pageSize']) ? $param['pageSize'] : 12;
            $where = ['dmd_goods.type_id'=>$this->type,'dmd_goods.is_delete'=>0];
            if($this->type == 1){
                $where['is_group'] = 0;
                $where['teaching_methods'] = 1;
            }
            $goods=Goods::find()->where($where)->orderBy('id DESC');//不加joinwith耗时7s，加了耗时4-5s
            if (!empty($param['searchData'])) {
                $search_data = $param['searchData'];
                if (!empty($search_data['goods_name'])) {
                    $goods->andWhere(['like', 'name', $search_data['goods_name']]);
                }
                if (!empty($search_data['mechanic_name'])) {
                    $mechanic=Mechanic::find()->where(['like','name',$search_data['mechanic_name']])->column(Fun::getSiteDb());
                    $goods->andWhere(['in', 'mechanic_id', $mechanic]);
                }
                if (!empty($search_data['cate_name'])) {
                    $cateids=[$search_data['cate_name']];
                    $category=Cate::findone([$search_data['cate_name']]);
                    $child_arr = [];
                    $parent_arr = explode(',',$category->arrparent_id);
                    if($category->parent_id == 0){
                        $child_arr = explode(",",$category->arrchild_id);
                    }elseif($category->parent_id != 0 && count($parent_arr) > 1){
                        $child_arr = explode(",",$category->arrchild_id);
                    }
                    $cates = array_merge($child_arr,$cateids);
                    $cate = Cate::find()->select('id')->Where(['in', 'id', $cates])->column();
                    $goods->andWhere(['in', 'cat_id', $cate]);
                }
                if (isset($search_data['is_shelve']) && $search_data['is_shelve'] != '') {
                    $goods->andWhere(['is_shelve'=>$search_data['is_shelve']]);
                }
            }
            $mids = Fun::getMechanicIds();
            if(!empty($mids)){
                $goods->andWhere(['mechanic_id'=>$mids]);
            }
            if(\Yii::$app->user->identity->role == 'business_director') {
                $DirectorMechanicIds = Fun::getDirectorMechanicIds();
                $goods->andWhere(['mechanic_id' => $DirectorMechanicIds]);

            }
            $pages = new Pagination(['totalCount' => $goods->count(), 'pageSize' => $pageSize]);
            isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
            $model = $goods->offset($pages->offset)->limit($pages->limit)->all();
            $ajax_object = new AjaxObject();
            $ajax_object->data = $this->getIndexArray($model);
            $ajax_object->pages = $pages;
            return $ajax_object;
        }
        return $this->controller->render('index',['role'=>$role,'tree'=>$tree]);
    }

    public function getCategory($type_id){
        $site_id=Fun::getSiteId();
        $cate_attr= CateAttr::find()->select(['cat_id'])->where(['or',['mobile_is_show'=>1],['pc_is_show'=>1]])->andWhere(['site_id'=>$site_id])->orderBy('pc_sort asc')->column();
        $category=Cate::find()->indexBy('id')->where(['in','id',$cate_attr])->andWhere(['type_id'=>$type_id])->asArray()->all();
        //$category = Cate::find()->indexBy('id')->where(['is_delete'=>0,'type_id'=>$type_id])->asArray()->all();
        $tree = (new Tree($category))->get_tree_select();
        return  $tree;
    }
    public function getIndexArray($model){
        if($this->type==1){
            $data=Fun::asArray($model, ['cate_name','mechanic_name','shelve_status','operate','class_time']);
            foreach($data as $key=>$v){
                $attr = Fun::getGoodsAttr($v['id']);
                $teacher_form = '';
                $data[$key]['teacher_name'] = isset($attr['teacher'])?$attr['teacher']:'';
                $data[$key]['room_name'] = isset($attr['classroom_name'])?$attr['classroom_name']:'';
                $data[$key]['max_number'] = isset($attr['max_number'])?$attr['max_number']:'';
                $data[$key]['course_name'] = isset($attr['course'])?$attr['course']:'';
                $data[$key]['course_name'] = isset($attr['course'])?$attr['course']:'';
                if(isset($attr['teacher_form'])){
                   if($attr['teacher_form'] == 0){
                       $teacher_form = '一对一';
                   }elseif($attr['teacher_form'] == 1){
                       $teacher_form = '小班制';
                   }else{
                       $teacher_form = '普通班';
                   }
                }
                $data[$key]['teacher_form'] = $teacher_form;
                $suitable_age = '';
                if(isset($attr['suitable_age']) && !empty($attr['suitable_age'])){
                    $str = substr($attr['suitable_age'], 1, -1 );
                    $arr = explode(',',$str);
                    if(count($arr) == 1){
                        $suitable_age = $arr[0];
                    }else{
                        $suitable_age = $arr[0].'-'.$arr[count($arr)-1];
                    }
                }
                $data[$key]['suitable_age'] = $suitable_age;
            }
        }elseif($this->type!=3){
            $data=Fun::asArray($model, ['cate_name','mechanic_name','brand_name','pro_operate']);
        }else{//等于3的时候舞台表演
            $data=Fun::asArray($model, ['cate_name','mechanic_name','brand_name','operate']);
        }
        return $data;
    }
}